import socket
import serial
import queue
from threading import Thread

ser=serial.Serial("/dev/ttyUSB0",115200,timeout=0.5)
print (ser.port)

qBuffer = queue.Queue() # 缓存队列 先进先出

HOST_IP = "172.28.28.241" # 树莓派IP
HOST_PORT = 8080 # 端口
print("Starting socket: TCP...")
#1.create socket object:socket=socket.socket(family,type)
socket_tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("TCP server listen @ %s:%d!" %(HOST_IP, HOST_PORT) )
host_addr = (HOST_IP, HOST_PORT)
#2.bind socket to addr:socket.bind(address)
socket_tcp.bind(host_addr)
#3.listen connection request:socket.listen(backlog)
socket_tcp.listen(1)
#4.waite for client:connection,address=socket.accept()
socket_con, (client_ip, client_port) = socket_tcp.accept()
print("Connection accepted from %s." %client_ip) # PC IP

ser.close() # 关闭
ser.open() #打开端口


def getData(): # 从 arduino或者 STM32 串口拿数据
    n = 1000
    cnt = 1
    while cnt <= n:
        try:
            data = ser.readline()
            #print(data)
            qBuffer.put(data)
            #send = qBuffer.get()
            #print(b"send")
            #print(send)
        except:
            continue

def sendToPC(): # 往PC发数据
    n = 1000
    cnt = 1
    while cnt <= n:
        send = qBuffer.get()
        #print(send)
        socket_con.send(send)

# 创建两个线程
try:
   t1 = Thread(target=getData)
   t2 = Thread(target=sendToPC)
   t1.start()
   t2.start()
except:
   print (b"Error: unable to start thread")